package bll

import (
	"context"
	"signal/utils"
	"time"

	"gitlab.local/backend/proto/dto"
	log "signal/collector/logger"
	"signal/lib/trace_log"
	"signal/model"
)

var Switches = &switches{}

// 服务端向设备发起远程一键启动
type switches struct {
}

func (s *switches) init() func() {
	return func() {}
}

// Switch 一键启动
func (s *switches) Switch(ctx context.Context, in *dto.SwitchRequest) error {
	var (
		id          uint8
		err         error
		requestKey  string
		config      = &model.SmartConfig{}
		alarmConfig = &model.AlarmConfig{}
	)

	since := time.Now()
	defer func() {
		trace_log.DebugLogger(in.Sn, "Switch 执行 data:", utils.ToJsonString(in), " config:", utils.ToJsonString(config), " err:", err, " 耗时:", time.Since(since))
	}()

	if in.HillAssist != nil {
		config.HillAssistEnable = true
		config.HillAssist = uint8(*in.HillAssist)
	}
	if in.SenselessUnlock != nil {
		config.RssiPowerOnEnable = true
		config.RssiPowerOn = uint8(*in.SenselessUnlock)
	}
	if in.PreventOutOfControl != nil {
		config.LoseControlEnable = true
		config.LoseControl = uint8(*in.PreventOutOfControl)
	}

	var packet *model.Packet
	if in.VibrationSensitivity != nil {
		alarmConfig.VibrationSensitivity = uint8(*in.VibrationSensitivity)
		if requestKey, id, err = Session.GetRequestID(in.Sn, model.CmdAlarmConfig); err != nil {
			log.Error("get request error ", err)
			return err
		}
		packet = model.BuildPacket(model.CmdAlarmConfig, id, alarmConfig.ToHexBytes())

	} else {
		if requestKey, id, err = Session.GetRequestID(in.Sn, model.CmdSmartConfig); err != nil {
			log.Error("get request error ", err)
			return err
		}
		packet = model.BuildPacket(model.CmdSmartConfig, id, config.ToHexBytes())
	}

	log.Infof("send switch to device: %X", packet.ToHexBytes())
	if _, err := Session.SyncRequest(in.Sn, requestKey, packet); err != nil {
		_ = Session.ReleaseID(in.Sn, id)
		return err
	}
	return nil
}
